<template>
  <div>
    <div style="font-size:18px;">消息管理</div>
    <hr>
    <br>
    
    <button @click="IMlogin()">登录</button>
    <button @click="IMregister()">注册</button>

    <div class="message-warp" >
        <div class="sidebar">
            <div class="m-card">
                <div class="top">
                    <img class="avatarImg" width="40" height="40" :alt="user.name" :src="shopData.shopLogo">
                    <p class="name">{{shopData.shopName}}</p>
                </div>
                <div class="bottom">
                    <input class="search" type="text" placeholder="search user..." v-model="search" @keydown.enter="filterSearch(userList)">
                </div>
            </div>
            <div class="m-list">
                <ul>
                    <li v-for="(item,index) in userList" :class="{ active: sessionIndex == index }" @click="select(item,index)">
                        <img class="avatarImg"  width="30" height="30" :alt="item.name" :src="item.oppositeImg">
                        <p class="name">{{item.serviceNick}}</p>
                    </li>
                </ul>
            </div>
        </div>
        <div class="main">
            <div class="m-message" ref="chatBoxScroll">  <!--  v-scroll-bottom="session.messages" -->
                <ul ref="chatBoxDemo" id='chatBoxDemo'>
                    <li v-for="item in chatList" :class="[item.from==userData.username? 'right':'left' ]">
                        <p class="time"><span>{{item.date}}</span></p>
                        <div class="main"> 
                            <img class="avatarImg" width="30" height="30" :src="item.headImg" />
                            <!-- <img v-if="item.from==userData.username" class="avatar" width="30" height="30" :src="item.headImg" /> -->
                            <div class="text">{{item.data}}</div>
                        </div>
                    </li>
                </ul>
            </div>
            <div class="m-text">
                <textarea placeholder="按 Enter 发送" v-model.trim="inputText" @keydown.enter="sendPrivateText(inputText)"></textarea>
                <div class="sendBar">
                  <button @click="sendPrivateText(inputText)">发送</button>
                </div>
            </div>
        </div>
    </div>

  </div>
</template>
<script>
    import $ from 'jquery';
    import Vue from 'vue';
    import { mapState,mapMutations } from "vuex";

  var schoolList
  export default {
    data() {
        return {
            search: '',
            sessionIndex: 0,
            user: {
                id: 1,
                name: 'sky',
                img: 'http://thirdwx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTIG37q83MibCic4UaSvZcupDBZJQVOdBHgdzScNUESeY4zz3oibt41f8BlLBP9BvohLQ9MdZXYficAr0g/132'
            },
            userList: [   // 用户列表
                // {
                //     id: 2,
                //     name: '站长素材',
                //     img: 'http://thirdwx.qlogo.cn/mmopen/vi_32/perebwOz2QVM60ia2Q22scu3cfcZkKgvBXUtAJ9TTkQesnhtU5q16T3MzQfL2f2PQFX12LNUadybNUf9BILYEPQ/132'
                // },
            ],
            chatList: [     // 会话列表
                // {
                //     id: 2,
                //     data: 'Hello，这是一个基于Vue + Webpack构建的简单chat示例，聊天记录保存在localStorge。简单演示了Vue的基础特性和webpack配置。',
                //     date: '2018-05-11 17:22:35',
                //     headImg: 'http://thirdwx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTIG37q83MibCic4UaSvZcupDBZJQVOdBHgdzScNUESeY4zz3oibt41f8BlLBP9BvohLQ9MdZXYficAr0g/132',
                //     from: 'lm',
                //     to: '',
                // },
                // {
                //     id: 3,
                //     data: '在的',
                //     date: '2018-05-11 17:22:35',
                //     headImg: 'http://thirdwx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTIG37q83MibCic4UaSvZcupDBZJQVOdBHgdzScNUESeY4zz3oibt41f8BlLBP9BvohLQ9MdZXYficAr0g/132',
                //     from: '15594818160',
                //     to: '',
                // },
            ],
            sessionIndex: 0,
            inputText: '',
            userData: {},
            shopData:{},
            goodsPhone: '',
            reciveNick: '',
            reciveImg: '',
        };
    },
    computed: {
        ...mapState({ 
            imIsLogin: state => state.IMISLOGIN,
        }),
        session () {
            return this.chatList[this.sessionIndex];
        },
    },
    filters: {
      // 将日期过滤为 hour:minutes
      time (date) {
          if (typeof date === 'string') {
              date = new Date(date);
          }
          return date.getHours() + ':' + date.getMinutes();
      }
    },
    directives: {
        // 发送消息后滚动到底部
        'scroll-bottom' () {
            Vue.nextTick(() => {
                // this.el.scrollTop = this.el.scrollHeight - this.el.clientHeight;
            });
        }
    },
    created() {
      // let userData = localStorage.getItem('userData')
      this.userData = JSON.parse(localStorage.getItem('userData'))
      this.shopData = JSON.parse(localStorage.getItem('shop'))
      this.getFriends(this.userData.username)
      if(!this.imIsLogin){  //判断是否登录
          this.IMlogin()   
      }else{
          
      }
    },
    mounted(){
        let self = this
        // this.getData()
        // console.log(111)
        // console.log(this.session)
        // console.log(this.$imConn)
        // console.log(this.$WebIM)
        this.$imConn.listen({
          onOnline: function() {  
              console.log('本机网络连接成功')
          }, 
          onOpened: function (message) { //登录成功
              console.log('登录成功', message)
              self.$store.commit('SET_IMLOGINSTATUS',true)
          },
          onClosed: function (message) { //连接关闭
              console.log('登录状态已关闭', message)
              self.$store.commit('SET_IMLOGINSTATUS',false)
          },
          onRoster: function(message) { //处理好友申请
              console.log(message);
          }, 
          onTextMessage: function ( message ) {
              console.log(message);
              console.log("有新的消息");
              var date = new Date().format("yyyy-MM-dd hh:mm:ss");
              let chatData = {
                  id: message.id,
                  date: date,
                  data: message.data,
                  headImg: self.reciveImg,
                  from: message.from,
                  to: message.to,
              }
              self.chatList.push(chatData)
              self.$nextTick(()=> {
                let aa = self.$refs.chatBoxDemo.offsetHeight
                console.log(aa)
                self.$refs.chatBoxScroll.scrollTop = aa;
              })
          },
          onPresence: function ( message ) {
              // 这里需要弹出面板标识有人要添加您为好友
              console.log(message)
              if(message.type == 'subscribe') {
                  that.privateUser = message.from;
                  that.privateUserPanel = true;
              }
          }
      });
    },
    methods: {
      getFriends(phone) {     //获取好友
        let data = { userName: phone }
        this.myajax("/userFriends/selectAll",data,res=>{
          if(res.code == 1000){
            // console.log(res)
            this.userList = res.data
            if(this.userList.length>0){
              this.select(this.userList[0],0)
            }
          }
        })
      },
      delFrends(item) {     //删除好友
        this.goodsPhone = item.serviceName
        let data = { userName: this.userData.username,serviceName: this.goodsPhone }
        this.myajax("/userFriends/deleteFriends",data,res=>{
          if(res.code == 1000){
            // console.log(res)
          }
        })
      },
      // getUserShopImg() {   //查自己的和别人的头像和nickname
      //     let data = {
      //         type: 3,
      //         from: this.userData.username,  //发消息的人
      //         to: this.goodsPhone,           //接受消息的人
      //     }
      //     // console.log(data)
      //     this.myajax('/userEntity/getUserShopImg',data,res=>{
      //       if(res.data.code==1000){
      //         console.log('自己的')
      //         console.log(res)
      //         this.imgAndNicknameInfo = res.data.data
      //       }else if(res.data.code==1011){
      //         console.log("参数错误")
      //       }
      //     })
      // },
      filterSearch (list) {
          list = list.filter(item => item.name.indexOf(this.search) > -1);
      },
      select (item,index) {
          this.sessionIndex = index;
          this.goodsPhone = item.serviceName
          this.reciveImg = item.oppositeImg
          this.reciveNick = item.serviceNick
          this.getChatList()
      },
      getChatList(){   //获取聊天记录
         // var data={
         //   pageNumber: this.pageNumber,
         //   pageSize:10,
         //   param:{
         //     userName : this.phone,
         //   }
         // }
         let data = {
              userName: this.userData.username,
              serviceName: this.goodsPhone,
          }
          this.myajax("/userEase/updateQueryList",data,res=>{
            if(res.code == 1000){
              // console.log(res)
              // this.reciveImg = res.data[0].userImg
              // this.reciveNick = res.data[0].userNick
              this.content2chatList(res.data)
            }
          })
      },
      sendPrivateText(msgText) {    //发消息
          let self = this;
          if(msgText){
            var date = new Date().format("yyyy-MM-dd hh:mm:ss");  
            var id = this.$imConn.getUniqueId();         // 生成本地消息id
            var msg = this.$WebIM.message('txt', id);    // 创建文本消息
            console.log()
            let chatData = {
                id: id,
                date: date,
                data: msgText,
                // headImg: this.avatar,
                headImg: this.shopData.shopLogo,    //店铺logo
                from: this.userData.username,
                to: this.goodsPhone,
            }
            //发送后清空输入框
            self.inputText = ""
            self.chatList.push(chatData)
            self.$nextTick(()=> {
              // self.chatList.push(chatData)
              let aa = self.$refs.chatBoxDemo.offsetHeight
              console.log(aa)
              self.$refs.chatBoxScroll.scrollTop = aa
            })
            msg.set({
                msg: msgText,                            // 消息内容
                to: this.goodsPhone,                          // 接收消息对象（用户id）
                roomType: false,
                success: function (id, serverMsgId) {
                    console.log('发送成功')
                    //发送后清空输入框
                    self.inputText = ""
                    var dataMessage = {
                        userName: self.userData.username,  //自己的用户名(手机号)
                        password: '123456',       //密码
                        serviceName: self.goodsPhone,  //接收人
                        content: msgText,
                        userProduct: "user",
                        // productId: self.goodsInfo.id,
                        // productName: self.goodsInfo.name,
                        readUser: "wd",             //已读未读
                        url: "www",                 //商品链接
                        // img: self.goodsInfo.logo,   //商品图像 
                        type: 3,  
                        userImg: self.shopData.shopLogo,       //发消息人图像
                        oppositeImg: self.reciveImg,      //收消息人图像
                        userNick: self.shopData.shopName,  //发消息人要显示给接收方的名字   后加的
                        serviceNick: self.reciveNick,  //接收方要显示给发消息人的名字    后加的
                    };
                    self.addMessage(dataMessage,"addChatMessage")
                },
                fail: function(e){
                    console.log("Send private text error");
                }
            });
            msg.body.chatType = 'singleChat';
            this.$imConn.send(msg.body);
          }else{
            self.$message({
              showClose: true,
              message: '发送内容不能为空',
              type: 'warning',
              duration: 2000,
            });
          }
      },
      addMessage(dataMessage,method){  //访问后台接口，添加或更新msg
          console.log('即将添加') 
          this.myajax('/userEase/'+method,dataMessage,res=>{
              if(res.code==1000){
                  console.log(res) 
                  console.log('添加成功') 
              }
          })
      },
      content2chatList(contentList) {
        let self = this
        var arr = []
        for(let i in contentList){
          var obj = {}
          obj.id = contentList[i].id
          obj.date = contentList[i].createDateName
          obj.data = contentList[i].content
          obj.headImg = contentList[i].userImg
          obj.from = contentList[i].userName
          obj.to = contentList[i].serviceName
          arr.push(obj)
        }
        this.chatList = arr
        this.$nextTick(()=> {
          let aa = self.$refs.chatBoxDemo.offsetHeight
          console.log(aa)
          self.$refs.chatBoxScroll.scrollTop = aa;
        })
        // setTimeout(function(){  scrollY
        //   let aa = self.$refs.chatBoxDemo.offsetHeight
        //   console.log(aa)
        //   self.$refs.scrollY.scrollTop = aa;
        // },1000)
      },
      IMlogin() { 
          let self = this;
          // console.log(123)
          var options = {
                  apiUrl: this.$WebIM.config.apiURL,
                  user: this.userData.username,
                  // pwd: this.password,
                  pwd: "123456",
                  appKey: this.$WebIM.config.appkey,
                  success: function (token) {
                      console.log('登录成功')
                  },
                  error: function(){
                  }
              };
          this.$imConn.open(options);
      },
      IMregister() {   //注册环信
          var option = {
              username: this.userData.username,
              // username: 15594818130,
              password: "123456",
              // nickname: '王哈哈',
              nickname: this.userData.realName,
              appKey: this.$WebIM.config.appkey,
              success: function () {
                  console.log('注册成功');
              },
              error: function () {
                  console.log('注册失败');
              },
              apiUrl: this.$WebIM.config.apiURL
          };
          this.$imConn.registerUser(option);
      },
      // getData() {
      //   let self=this;
      //   this.myajax("/user_entity/list",this.listQuery,res=>{
      //     if(res.code == 1000){
      //       console.log(res)
      //       self.tableData = res.data.list
      //       self.total = res.data.total
      //     }
      //   })
      // },
      // handleDelete(row) {
      //   console.log(row);
      //   let self = this
      //   this.$confirm('此操作将永久删除该投诉, 是否继续?', '提示', {
      //     confirmButtonText: '确定',
      //     cancelButtonText: '取消',
      //     type: 'warning'
      //   }).then(() => {
      //     self.myajax("/complain/deleteById",{id:row.id},(res)=>{
      //       console.log(res)
      //       if(res.code==1000){
      //         self.getData()
      //         self.$message({
      //           type: 'success',
      //           message: '删除成功!',
      //           duration: 1000
      //         });
      //       }
      //     })
      //   }).catch(() => {
        
      //   }); 
      // },
    }
  };
</script>
<style scoped>
    ul{
        list-style: none;
    }
    .message-warp {
      margin: 20px auto;
      width: 800px;
      height: 600px;
      overflow: hidden;
      border-radius: 3px;
    }    
    .message-warp  .sidebar, .main {
        height: 100%;   
    }
    .message-warp  .sidebar {
        float: left;
        width: 200px;
        color: #f4f4f4;
        background-color: #2e3238;
        /*background-color: rgb(214,242,255);*/
    }
    .message-warp  .main {
        position: relative;
        overflow: hidden;   
        background-color: #eee;
    }
    .message-warp  .m-text {
        position: absolute;
        width: 100%;
        bottom: 0;
        left: 0;
    }
    .message-warp  .m-message {
      box-sizing: border-box;
        height: calc(100% - 160px);
    }


    .m-card {
        padding: 12px;
        border-bottom: solid 1px #24272C;
    }   
    .m-card  div.bottom {
        margin-top: 10px;
    }
    .m-card  .avatarImg {
        border-radius: 2px;
    } 
    .m-card  .avatarImg,.m-card .name {
        vertical-align: middle;
    }
        
    .m-card  .name {
        display: inline-block;
        margin: 0 0 0 15px;
        font-size: 16px;
    }
    .m-card  .search {
        padding: 0 10px;
        width: 100%;
        font-size: 12px;
        color: #fff;
        height: 30px;
        line-height: 30px;
        border: solid 1px #3a3a3a;
        border-radius: 4px;
        outline: none;
        background-color: #26292E;
    }


    .m-list  li {
        padding: 12px 15px;
        border-bottom: 1px solid #292C33;
        cursor: pointer;
        transition: background-color .1s;
    }      
    .m-list  li:hover {
        background-color: rgba(255, 255, 255, 0.03);
    }
    .m-list  li.active {
        background-color: rgba(255, 255, 255, 0.1);
    }
    .m-list  li  .avatarImg,.m-list  li .name {
        vertical-align: middle;
    }
    .m-list  li  .avatarImg {
        border-radius: 2px;
    }
    .m-list  li  .name {
        display: inline-block;
        margin: 0 0 0 15px;
    }
  

    .m-message {
        padding: 10px 15px;
        overflow-y: scroll;
    }    
    .m-message li {
        margin-bottom: 15px;
    }
    .m-message .time {
        margin: 7px 0;
        text-align: center;
    }   
    .m-message .time > span {
        display: inline-block;
        padding: 0 18px;
        font-size: 12px;
        color: #fff;
        border-radius: 2px;
        background-color: #dcdcdc;
    }  
    .m-message .text {
        display: inline-block;
        position: relative;
        padding: 0 10px;
        max-width: calc(100% - 100px);
        min-height: 30px;
        line-height: 2.5;
        font-size: 12px;
        text-align: left;
        word-break: break-all;
        background-color: #fafafa;
        border-radius: 4px;
    }    
    .m-message .text:before {
        content: " ";
        position: absolute;
        top: 9px;
        right: 100%;
        border: 6px solid transparent;
        border-right-color: #fafafa;
    }
    .m-message li.left {
        text-align: left;
    }
    .m-message li.left .avatarImg {
        float: left;
        margin: 0 10px 0 0;
        border-radius: 3px;
    }   
    .m-message li.right .avatarImg {
        float: right;
        margin: 0 0 0 10px;
        border-radius: 3px;
    }
    .m-message  .right {
        text-align: right;
    }    
    .m-message  .right  .avatarImg {
        float: right;
        margin: 0 0 0 10px;
    }
    .m-message  .right  .text {
        background-color: #b2e281;
    }
    .m-message  .right  .text:before {
        right: inherit;
        left: 100%;
        border-right-color: transparent;
        border-left-color: #b2e281;
    }
        
        

    .m-text {
        height: 160px;
        border-top: solid 1px #ddd;
        border-right: 1px solid #eee;
        
        box-sizing: border-box;
    }  
    .m-text .sendBar{
      height: 40px;
      box-sizing: border-box;
      background: #fff;
      border-bottom: 1px solid #eee;
    }  
    .m-text .sendBar button{
      float: right;
      margin-right: 20px;
      width: 60px;
      height: 30px;
      line-height: 30px;
      color: #000;
    }
    .m-text  textarea {
      display: block;
      box-sizing: border-box;
      padding-top: 10px;
      padding-left: 4px;
      height: 119px;
      width: 100%;
      border: none;
      outline: none;
      font-family: "Micrsofot Yahei";
      resize: none;
    }
</style>
